在前一篇我們已經完成了 FastAPI + NASA API 的 baseline,這一篇要把它升級成 AI 可直接使用的 MCP 工具伺服器。
我們需要用到的是 fastapi-mcp
這個 library,它可以把 FastAPI 的 endpoint 包裝成 MCP 工具,歡迎到他們的開源專案去看看(https://github.com/tadata-org/fastapi_mcp)。
前一篇 requirements.txt
已經包含 fastapi-mcp
,所以這篇不用額外安裝。
因為fastapi-mcp保留了 FastAPI 的原有功能,所以我們只需要在 app/main.py
中增加 MCP Server 的初始化。
在 import 區塊中加入:
from fastapi_mcp import FastApiMCP
在 app
初始化後,加入 MCP 的初始化:
記得要加在定義好的routes後面
# Initialize and mount MCP server
mcp = FastApiMCP(
app,
name="nasa-mcp-server",
description="NASA data access through MCP protocol"
)
mcp.mount_sse(app, mount_path="/mcp")
這樣一來,MCP 工具就會和 FastAPI 同時掛在一起。加入的 /mcp
路徑會是 MCP 的 endpoint。
完整main.py檔案:main.py
安裝完後啟動:
python main.py
然後在瀏覽器或 Postman 中打開 http://localhost:8000/mcp
,你應該會看到類似以下的回應:
event: endpoint
data: /mcp/messages/?session_id=0ecb2715e7bf4300941c04623a3b5d90
第三篇我們會示範如何在 Kiro 或 VS Code 加上 MCP 設定檔,讓 AI 能 discover 與使用這些工具。